const express = require("express");
//创建路由
let atlas = express.Router();
//路径包
const path = require("path");
//获取启动项目录
const rootDir = process.cwd();
//用于临时令牌
const crypto = require('crypto');
const jwt = require('jsonwebtoken');

//引入方法
//引入授权中间件
const authenticateToken = require(path.join(rootDir, "/middlewares/authMiddleware"));
//引入上传图片中间件
const uploadfile = require(path.join(rootDir, "/middlewares/uploadMiddleware"));
//引入移动检测中间件
const mobiledetect = require(path.join(rootDir, './middlewares/mobiledetect'));

//引入数据表
let atlasloki = require(path.join(rootDir, "lokisheets/atlasDB"));

//创建图片上传中间件
function imgUpload(uploadPath) {
    const upload = uploadfile.createUploader(uploadPath, {
        //限制文件类型
        allowedMimeTypes: ['image/jpeg', 'image/png', 'image/webp'],
        //限制文件大小
        limits: { fileSize: 40 * 1024 * 1024 }
    });

    return imgMulter(upload);
}
//图片保存方法
function imgMulter(multer) {
    return (req, res) => {
        return new Promise((resolve, reject) => {
            multer.fields([
                { name: 'singleImg', maxCount: 1 },    // 封面图
                { name: 'arrayImg', maxCount: 50 }     // 图集图片
            ])(req, res, (err) => {
                if (err) return reject(err);

                let json = {
                    sin: {},
                    arr: [],
                    webData: {}
                };

                if (req.files['singleImg']) {
                    json.sin.name = req.files['singleImg'][0].originalname;
                    json.sin.path = req.files['singleImg'][0].path;
                }

                if (req.files['arrayImg']) {
                    req.files['arrayImg'].forEach(data => {
                        json.arr.push({
                            name: data.originalname,
                            path: data.path
                        });
                    });
                }

                json.webData = { ...req.body, ...req.query };
                resolve(json);
            });
        });
    };
}
// 生成一次性临时认证码
const tempTokens = new Map();


//区分手机电脑页面中间件
atlas.use(mobiledetect);

//图集根路由
atlas.get("/", (req, res) => {
    //process.cwd()是启动文件的绝对路径
    if (req.isMobile) {
        //这是手机端页面
        res.sendFile(process.cwd() + "/static/html/mobile/atlas/atlasindex.html");
    } else {
        //这是电脑端页面
        res.sendFile(process.cwd() + "/static/html/computer/atlas/atlasindex.html");
    }
});


//创建图集路由
atlas.use("/createatlas", authenticateToken.authenticateToken, async (req, res) => {
    try {
        let webData = { ...req.body, ...req.query };

        let saveData = {
            User_id: req.user.userid,
            Atlasname: webData.Atlasname
        }
        // let result = await modelfunc.createOneModel(atlassheets, saveData, saveData);
        let result = await atlasloki.create(saveData);

        if (result.success) {
            res.json({ message: { success: true, data: result } });
        } else {
            res.json({ message: { success: true, data: "创建失败" } });
        }
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

//图集查找路由
atlas.use("/findatlas", authenticateToken.authenticateToken, async (req, res) => {
    try {
        let webData = { ...req.body, ...req.query };

        const User_id = req.user.userid;
        let findData = {
            condition: {
                $and: [
                    { User_id },
                    webData.condition
                ]
            },
            limit: webData.limit
        }
        //这里还没有更新，需要等查找方法修改后进行
        // let result = await modelfunc.findManyModel(atlassheets, findData.condition, findData.limit);
        let result = await atlasloki.find(findData.condition);
        if (result.success) {
            res.json({ message: { success: true, data: result.data } });
        } else {
            res.json({ message: { success: false, data: "查询不到数据" } });
        }
    } catch (error) {
        res.send(error);
    }
});


//删除图片路由
atlas.use("/deleteimg", authenticateToken.authenticateToken, async (req, res) => {
    let webData = { ...req.body, ...req.query };

    let saveData = {
        User_id: req.user.userid,
        Atlas_id: webData.Atlas_id,
        atlasimgs: []
    }
    webData.Atlasimgs.forEach(data => {
        saveData.atlasimgs.push({ "imgname": data });
    });

    let result = await atlasloki.deletearray(saveData);

    if (result.success) {
        res.json({ message: { success: true, data: result } });
    } else {
        res.json({ message: { success: true, data: "删除失败" } });
    }
});

//删除图集路由
atlas.use("/deleteatlas", authenticateToken.authenticateToken, async (req, res) => {
    let webData = { ...req.body, ...req.query };

    let findData = {
        User_id: req.user.userid,
        Atlas_id: webData.Atlas_id
    }
    let result = await atlasloki.delete(findData);
    // let result = await modelfunc.deleteOneModel(atlassheets, findData);
    if (result.success) {
        res.json({ message: { success: true, data: result } });
    } else {
        res.json({ message: { success: true, data: "删除失败" } });
    }
});

//返回一次性临时认证码
atlas.use('/gettempcode', (req, res) => {
    try {
        const authHeader = req.headers.authorization;
        if (!authHeader) return res.status(401).send('未授权');

        // 解码原始令牌获取用户信息
        const originalToken = authHeader.split(' ')[1];

        const decoded = jwt.verify(originalToken, process.env.JWT_SECRET);
        let userid = decoded.userid;

        // 创建临时令牌并存储完整用户信息
        const tempToken = crypto.randomBytes(32).toString('hex');

        tempTokens.set(tempToken, {
            userid,
            originalToken,
            expiresAt: Date.now() + 60 * 60 * 1000 // 60分钟后过期
        });

        res.json({ tempToken });
    } catch (err) {
        console.error("Token 验证失败:", err);
        res.status(401).json({ error: "无效的 Token" });
    }
});


//展示图集路由
atlas.use("/show:name", async (req, res) => {

    // const { tempToken } = req.query;
    const tempToken = req.query.tempToken;

    // 1. 检查临时令牌是否存在
    if (!tempTokens.has(tempToken)) {
        return res.status(401).json({ error: "无效的临时令牌" });
    }

    const tokenData = tempTokens.get(tempToken);
    // console.log("临时令牌" + req.query);

    if (!tokenData || tokenData.expiresAt < Date.now()) {
        tempTokens.delete(tempToken);
        return res.status(401).send('无效或过期的临时令牌');
    }
    let atlas_id = req.params.name;
    // // 直接使用存储的用户ID
    const userId = tokenData.userid;
    //查找数据
    let findData = {
        User_id: userId,
        Atlas_id: atlas_id
    }

    let result = await atlasloki.find(findData)
    if (!result.data[0]) {
        res.send("不存在数据");
    }
    else {
        if (req.isMobile) {
            //这是手机端页面
            res.render("mobile/atlasejs/atlasshow", { json: result.data[0] });
        } else {
            //这是电脑端页面
            res.render("computer/atlasejs/atlasshow", { json: result.data[0] });
        }
    }


});

//图集添加图片路由
atlas.use("/updataatlas:name", authenticateToken.authenticateToken, async (req, res) => {
    try {
        let findAtlasData = {
            User_id: req.user.userid,
            Atlas_id: req.params.name
        }
        // let resultModel = await modelfunc.findOneModel(atlassheets, findAtlasData);
        let resultModel = await atlasloki.find(findAtlasData);
        let atlasfilename = resultModel.data[0].Atlas_id.toString();
        //图集封面文件夹名
        let atlasCoverUrl = path.join("atlas", atlasfilename, "atlasCover");
        //图集图片文件夹名
        let atlasImgUrl = path.join("atlas", atlasfilename, "atlasImg");

        let atlasPath = {
            "singleImg": atlasCoverUrl,
            "arrayImg": atlasImgUrl
        }
        let resultUpload = await imgUpload(atlasPath)(req, res);


        //验证上传过来的数据

        let images = [];

        //保存数据
        let setSaveData = {
            //查询条件
            User_id: req.user.userid,
            Atlas_id: req.params.name,
            //保存数据
            Atlasname: resultUpload.webData.Atlasname, //图集名称
            Atlasmessage: resultUpload.webData.Atlasmessage, //图集简介
        }
        //单个封面存在
        if (resultUpload.sin) {
            setSaveData.Atlascovername = resultUpload.sin.name; //封面名称
            setSaveData.Atlascoverurl = resultUpload.sin.path; //封面路径
        }
        //多张图片存在
        if (resultUpload.arr) {
            resultUpload.arr.forEach(arrayimg => {
                let imgs = {
                    imgname: arrayimg.name,
                    imgurl: arrayimg.path
                }
                images.push(imgs);
            });
            setSaveData.Atlasimgs = images;
        }

        let result = await atlasloki.update(setSaveData);

        if (result.success) {
            res.json({ message: { success: true, data: result } });
        } else {
            res.json({ message: { success: true, data: "更新失败" } });
        }
    } catch (error) {
        console.log(error);
        res.status(500).json({ error: error.message });
    }
});

//删除图片展示路由
atlas.use("/deleteimg:name", async (req, res) => {


    // const { tempToken } = req.query;
    const tempToken = req.query.tempToken;

    // 1. 检查临时令牌是否存在
    if (!tempTokens.has(tempToken)) {
        return res.status(401).json({ error: "无效的临时令牌" });
    }

    const tokenData = tempTokens.get(tempToken);

    if (!tokenData || tokenData.expiresAt < Date.now()) {
        tempTokens.delete(tempToken);
        return res.status(401).send('无效或过期的临时令牌');
    }
    let atlas_id = req.params.name;
    // // 直接使用存储的用户ID
    const userId = tokenData.userid;
    //查找数据
    let findData = {
        User_id: userId,
        Atlas_id: atlas_id
    }

    let result = await atlasloki.find(findData);
    if (!result.data[0]) {
        res.send("不存在数据");
    }
    else {
        if (req.isMobile) {
            //这是手机端页面
            res.render("mobile/atlasejs/deleteimg", { json: result.data[0] });
        } else {
            //这是电脑端页面
            res.render("computer/atlasejs/deleteimg", { json: result.data[0] });
        }
    }
});

//添加图片展示路由
atlas.use("/addimg:name", async (req, res) => {

    // const { tempToken } = req.query;
    const tempToken = req.query.tempToken;

    // 1. 检查临时令牌是否存在
    if (!tempTokens.has(tempToken)) {
        return res.status(401).json({ error: "无效的临时令牌" });
    }

    const tokenData = tempTokens.get(tempToken);

    if (!tokenData || tokenData.expiresAt < Date.now()) {
        tempTokens.delete(tempToken);
        return res.status(401).send('无效或过期的临时令牌');
    }
    let atlas_id = req.params.name;
    // // 直接使用存储的用户ID
    const userId = tokenData.userid;
    //查找数据
    let findData = {
        User_id: userId,
        Atlas_id: atlas_id
    }

    let result = await atlasloki.find(findData);
    // let result = await modelfunc.findOneModel(atlassheets, findData);
    if (!result.data[0]) {
        res.send("不存在数据");
    }
    else {
        if (req.isMobile) {
            //这是手机端页面
            res.render("mobile/atlasejs/addimg", { json: result.data[0] });
        } else {
            //这是电脑端页面
            res.render("computer/atlasejs/addimg", { json: result.data[0] });
        }
    }

});


module.exports = atlas;